local ConfigLoader = require("config.loader")
local Settings = require("config.settings")
local config = ConfigLoader.load(Settings.CURRENT_GAME)
local logger = require "utils.logger"
local tslib = require "TSLib"

local M = {}

function M.testBaiduOCR()
    -- 识别区域
    local region = { 775, 732, 806, 774 }
    local testImgPath = userPath() .. "/res/test_ocr.png"
    logger.info("截图路径：" .. testImgPath)

    -- 截图操作
    snapshot(testImgPath, region[1], region[2], region[3], region[4])

    -- OCR 参数配置
    local ocr_params = {
        language_type = "ENG",
        detect_direction = "true",
        ocrType = 1
    }

    -- 调用 OCR 服务
    local success, result = pcall(function()
        local code1, access_token = getAccessToken(
            config.BAIDU_OCR.API_KEY, 
            config.BAIDU_OCR.SECRET_KEY
        )
        if not code1 then return false, access_token end
    -- 已移除 resizeImage 调用
    
    -- 压缩图像至合理尺寸
    local image_data = ts.base64Encode(testImgPath)
    local url_encoded = ts.urlEncode(image_data)
        
        local post_data = "image="..url_encoded
        
        local code2, header, body = tslib.httpPost(
            "https://aip.baidubce.com/rest/2.0/ocr/v1/numbers?access_token="..access_token,
            {["Content-Type"] = "application/x-www-form-urlencoded"},
            post_data
        )
        return code2, body
    end)
    -- 处理识别结果

    -- 解析JSON结果
    local data = cjson.decode(result)
    local json_ok = data ~= nil

    if json_ok and data.words_result and #data.words_result > 0 then
        logger.info("OCR识别成功")
        logger.info("识别结果:", data.words_result[1].words)
        local number = tonumber(data.words_result[1].words)
        if number then
            logger.info("成功提取数字：" .. number)
            return number
        end
    else
        logger.error("OCR识别失败 状态码:" .. tostring(data.error_code or '未知') .. " 信息:" .. tostring(data.error_msg or '无'))
    end
    return nil
end

return M
